<template>
	<view class="asset-detail-container">
    <!-- 使用系统导航栏返回与标题，移除自定义头部 -->

    <view class="cell">
			<text class="label">资产编号</text>
			<text class="value">{{ detail.assetNo }}</text>
		</view>
    <view class="cell">
			<text class="label">模具名称</text>
      <text class="value bold">{{ detail.name }}</text>
		</view>
		<view class="cell">
			<text class="label">位置</text>
			<text class="value">{{ detail.location }}</text>
		</view>
		<view class="cell">
			<text class="label">规格型号</text>
			<text class="value">{{ detail.model }}</text>
		</view>
		<view class="cell">
			<text class="label">类型</text>
			<text class="value">{{ detail.category }}</text>
		</view>
		<view class="cell">
			<text class="label">使用部门</text>
			<text class="value">{{ detail.department }}</text>
		</view>
		<view class="cell">
			<text class="label">操作人员</text>
			<text class="value">{{ detail.operator }}</text>
		</view>
		<view class="cell">
			<text class="label">购入日期</text>
			<text class="value">{{ detail.buyDate }}</text>
		</view>
		<view class="cell">
			<text class="label">投产日期</text>
			<text class="value">{{ detail.prodDate }}</text>
		</view>

		<!-- 模具图片数量 -->
		<view class="cell">
			<text class="label">模具图片</text>
			<text class="value">{{ detail.photos ? detail.photos.length : 0 }}</text>
		</view>
		<!-- 模具图片预览 -->
		<view class="photos-row" v-if="detail.photos && detail.photos.length">
			<image v-for="(p,idx) in detail.photos" :key="idx" :src="resolveImageUrl(p)" class="photo" @click="previewPhoto(idx)"></image>
		</view>
		<view class="photos-row" v-else>
			<text class="no-photo">暂无图片</text>
		</view>

		<view class="section">
			<text class="section-title">备注</text>
			<text class="remark">{{ detail.remark }}</text>
		</view>

    <view class="bottom-actions">
      <button class="btn small" @click="openRepairHistory">维修履历</button>
    </view>
	</view>
</template>

<script>
import assetApi from '@/api/asset/asset.js'
import { getDeviceType } from '@/api/dict/deviceType.js'
export default {
		data() {
			return {
			detail: { assetNo:'', name:'', location:'', model:'', category:'', department:'', operator:'', buyDate:'', prodDate:'', photos:[], remark:'' }
			}
		},
		onLoad(query) {
			// 若未手动设置 BASE_URL，则使用与请求一致的默认值，避免需要手动在控制台设置
			try {
				if (!uni.getStorageSync('BASE_URL')) {
					uni.setStorageSync('BASE_URL', 'http://127.0.0.1:8081');
				}
				// 读取后端yml中的 MinIO endpoint（已知为 io.brightholdings.cn ），作为默认前缀
				if (!uni.getStorageSync('MINIO_BASE')) {
					uni.setStorageSync('MINIO_BASE', 'https://io.brightholdings.cn');
				}
			} catch(e) {}
			const assetNo = query && query.assetNo;
			if (assetNo) this.fetchDetail(assetNo);
		},
		methods: {
			goBack() { uni.navigateBack({ delta: 1 }); },
			openMore() { uni.showActionSheet({ itemList: ['编辑','维保计划','二维码'], success:()=>{} }); },
			openRepairHistory() { uni.navigateTo({ url: '/pages/asset/repair-history?assetNo='+this.detail.assetNo }); },
			// 解析图片URL：支持相对路径/绝对路径
			resolveImageUrl(u) {
				if (!u) return '';
				// 已是绝对URL
				if (/^https?:\/\//i.test(u)) return u;
				// MinIO前缀
				const minioBase = uni.getStorageSync('MINIO_BASE');
				const bucket = 'smart-maintenance';
				if (minioBase) {
					// u 可能是：/bucket/xxx.png、bucket/xxx.png、仅文件名xxx.png
					if (u.startsWith('/')) return minioBase.replace(/\/$/, '') + u;
					if (u.includes('/')) return minioBase.replace(/\/$/, '') + '/' + u;
					// 只有文件名时补齐 bucket
					return minioBase.replace(/\/$/, '') + '/' + bucket + '/' + u;
				}
				// 走网关BASE_URL
				const base = uni.getStorageSync('BASE_URL') || 'http://127.0.0.1:8081';
				return base.replace(/\/$/, '') + (u.startsWith('/') ? u : '/' + u);
			},
			previewPhoto(index) {
				const urls = (this.detail.photos || []).map(this.resolveImageUrl);
				if (urls.length) {
					uni.previewImage({ current: index, urls });
				}
			},
			async fetchDetail(assetNo) {
				try {
            const res = await assetApi.getAsset(assetNo);
            const d = res.data || res || {};
            const rawPhotos = (() => {
						if (Array.isArray(d.imageUrls)) return d.imageUrls;
						if (Array.isArray(d.images)) return d.images;
						if (typeof d.imageUrls === 'string') {
                    try {
                        const arr = JSON.parse(d.imageUrls);
								if (Array.isArray(arr)) return arr;
                    } catch(e) {
                        const s = String(d.imageUrls || '').trim();
                        // 优先用正则提取被引号包裹或以 http/https、/ 开头的路径片段
                        const hits = s.match(/https?:\/\/[^\s"\],]+|\/[^^\s"\],]+/g);
                        if (hits && hits.length) return hits;
                        // 回退：逗号切分
                        return s.split(',').map(x => x.replace(/[\[\]"]+/g,'').trim()).filter(Boolean);
                    }
						}
						return [];
            })();
            // 归一化与过滤无效项
            const photos = rawPhotos
              .map(p => this.resolveImageUrl(String(p || '').trim()))
              .filter(u => /^https?:\/\//i.test(u));
					this.detail = {
              assetNo: d.assetNo || d.id || assetNo,
              name: d.assetName || d.deviceName || d.name || '-',
              location: d.location || d.assetLocation || d.locationName || '-',
              model: d.model || d.modelNo || d.specModel || d.specNo || '-',
              category: d.category || d.categoryName || d.type || d.typeName || d.equipmentTypeName || d.equipmentType || d.equipmentTypeCode || d.categoryId || '-',
              department: d.department || d.deptName || d.useDept || '-',
              operator: d.operator || d.operatorName || d.user || '-',
              buyDate: d.buyDate || d.purchaseDate || '-',
              prodDate: d.prodDate || d.commissioningDate || '-',
              photos: photos,
              remark: d.remark || d.memo || ''
					}
					// 若类型是编码，尝试查询字典转换中文
					if (this.detail.category && /[A-Z_\-0-9]+/.test(this.detail.category)) {
						try {
							const dictRes = await getDeviceType(this.detail.category);
							const dict = dictRes.data || dictRes;
							if (dict && (dict.name || dict.typeName)) {
								this.detail.category = dict.name || dict.typeName;
							}
						} catch(e) {}
					}
				} catch(e) {
					console.error('获取资产详情失败', e);
					uni.showToast({ title:'获取详情失败', icon:'none' });
				}
			}
		}
	}
</script>

<style>
	.asset-detail-container { min-height:100vh; background:#fff; padding-bottom:120rpx; }
	.top-bar { display:flex; align-items:center; justify-content:space-between; padding:20rpx 24rpx; }
  .title { font-size: 32rpx; font-weight:600; }
	.back-area,.more-area { width:60rpx; text-align:center; color:#666; }
	.cell { display:flex; justify-content:space-between; padding: 26rpx 28rpx; border-bottom:1rpx solid #f1f1f1; }
	.label { color:#666; font-size:26rpx; }
  .value { color:#333; font-size:26rpx; }
  .value.bold { font-weight: 700; }
	.photos-row { display:flex; gap:20rpx; padding: 20rpx 28rpx; }
	.photo { width: 120rpx; height: 120rpx; background:#eee; border-radius: 8rpx; }
	.section { padding: 20rpx 28rpx; }
	.section-title { display:block; font-weight:600; margin-bottom: 12rpx; }
	.remark { display:block; line-height:1.6; color:#444; }
	.bottom-actions { position:fixed; bottom: 20rpx; left:0; right:0; display:flex; justify-content:center; }
.btn { width: 90%; background:#007aff; color:#fff; border:none; border-radius: 12rpx; padding: 20rpx 0; }
.btn.small { width: 60%; padding: 16rpx 0; font-size: 28rpx; }
</style>

